#!/usr/bin/env python3

import socket
import os
import signal

def outRecvData(sd):
    data, addr = sd.recvfrom(1024)

    data = data.decode()

    if data == 'exit':
        return None

    print("\033[s\033[1;1H\033[2K客户端接受到(%s): %s\033[u"
                % (addr[0], data), end='', flush=True)

    return addr

def myExit(sig, stack):
    os._exit(0)

def main():
    signal.signal(signal.SIGTERM, myExit)

    sd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    addr = ('3.3.3.9', 9000)

    print("\033[2J", end="", flush=True)

    if os.fork() == 0:
        while outRecvData(sd):
            pass
    else:
        while True:
            data = input("\033[5;1H\033[2K客户端发送: ")
            sd.sendto(data.encode(), addr)
            if data == 'exit':
                break

    sd.close()
    os.kill(0, signal.SIGTERM)


if __name__ == "__main__":
    main()
